package com.example.weatherapp7229.util;


import android.text.TextUtils;

import com.example.weatherapp7229.db.City;
import com.example.weatherapp7229.db.County;
import com.example.weatherapp7229.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Utility {

    //解析网络返回的json数据，并存储在数据库表中

    /**
     * @param response
     * @return true
     */
    public static boolean handleProvinceResponse(String response) {
        if (!TextUtils.isEmpty(response)) {
            try {
                JSONArray jsonArray = new JSONArray(response);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject o = jsonArray.getJSONObject(i);
                    Province province = new Province();
                    province.setProvinceName(o.getString("name"));
                    province.setProvinceCode(o.getInt("id"));
                    province.save();
                }
                return true;
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }
        return false;

    }

    public static boolean handleCityResponse(String response, int provinceId) {
        if (!TextUtils.isEmpty(response)) {
            try {
                JSONArray allCities = new JSONArray(response);
                for (int i = 0; i < allCities.length(); i++) {
                    JSONObject cityObject = allCities.getJSONObject(i);
                    City city = new City();
                    city.setProvinceId(provinceId);
                    city.setCityName(cityObject.getString("name"));
                    city.setCityCode(cityObject.getInt("id"));
                    city.save();

                }
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
        return false;
    }
    public static boolean handleCountyResponse(String response, int cityId) {
        if (!TextUtils.isEmpty(response)) {
            try {
                JSONArray allCounties = new JSONArray(response);
                for (int i = 0; i < allCounties.length(); i++) {
                    JSONObject countyObject = allCounties.getJSONObject(i);
//                    City city = new City();
                    County county=new County();
//                    city.setProvinceId(provinceId);
                    county.setCityId(cityId);
//                    city.setCityName(cityObject.getString("name"));
                    county.setCountyName(countyObject.getString("name"));
//                    city.setCityCode(cityObject.getInt("id"));
                    county.setWeatherId(countyObject.getString("weather_id"));
//                    city.save();
                    county.save();

                }
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
        return false;
    }
}
